import random

from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from . import constants
from meiduo_mall.libs.captcha.captcha import captcha
from django import http
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms


class ImageCodeView(View):

    def get(self, request, uuid):
        # 接收
        # 验证

        # 处理：
        # 1.生成图片的文本、数据
        text, code, image = captcha.generate_captcha()

        # 2.保存图片文本，用于后续与用户输入值对比
        redis_cli = get_redis_connection('image_code')
        redis_cli.setex(uuid, constants.IMAGE_CODE_EXPIRES, code)

        # 响应：输出图片数据
        return http.HttpResponse(image, content_type='image/png')


class SmsCodeView(View):
    def get(self, request, mobile):
        uuid = request.GET.get('image_code_id')
        print(uuid)
        image_code = request.GET.get('image_code')
        print(image_code)

        redis_cli = get_redis_connection('sms_code')
        if redis_cli.get(mobile + '_flag') is not None:
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '别恶意刷短信验证码'})

        if not all([uuid, image_code]):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数不完整'})
        #        验证图形验证码是否正确
        redis_cli_1 = get_redis_connection('image_code')
        image_code_redis = redis_cli_1.get(uuid)
        if image_code_redis is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已经过期，请刷新图片'})
        redis_cli_1.delete(uuid)
        if image_code_redis.decode().lower() != image_code.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码错误'})

        #         生成随机六位数
        sms_code = '%06d' % random.randint(0, 999999)
        #        把生成的短信验证码存入redis
        #        使用管道优化和redis之间交互
        #         获取管道对象
        redis_pl = redis_cli.pipeline()
        redis_pl.setex(mobile, constants.SMS_CODE_EXPIRES, sms_code)
        redis_pl.setex(mobile + '_flag', constants.SMS_CODE_FLAG, 1)
        redis_pl.execute()
        #         redis_cli.setex(mobile,constants.SMS_CODE_EXPIRES,sms_code)
        #         redis_cli.setex(mobile+'_flag',constants.SMS_CODE_FLAG,1)
        # 开始发短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, constants.SMS_CODE_EXPIRES / 60], 1)
        # print(sms_code)
        # 通过delay调用，可以将任务加到队列中，交给celery执行
        send_sms.delay(mobile,sms_code)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '图形验证码错误'})
